---@class WenheYanbing.Combat
local Combat = class("WenheYanbing.Combat")

function Combat:initialize(player1, player2)
    self.player1 = player1
    self.player2 = player2
    self.log = {}
    self.currentAttacker = 1
end

-- 执行完整战斗
function Combat:execute()
    self:logEvent("战斗开始")
    
    -- 复制棋盘避免修改原数据
    local board1 = self:copyBoard(self.player1.board)
    local board2 = self:copyBoard(self.player2.board)
    
    -- 触发战斗开始效果
    self:triggerCombatStart(board1, self.player1)
    self:triggerCombatStart(board2, self.player2)
    
    -- 决定先手
    self.currentAttacker = math.random(1, 2)
    self:logEvent((self.currentAttacker == 1 and self.player1.name or self.player2.name) .. "获得先手")
    
    local round = 1
    local maxRounds = 50
    
    while #board1 > 0 and #board2 > 0 and round <= maxRounds do
        self:logEvent("=== 第" .. round .. "回合 ===")
        
        if self.currentAttacker == 1 then
            self:resolveAttack(board1, board2, self.player1, self.player2)
            self.currentAttacker = 2
        else
            self:resolveAttack(board2, board1, self.player2, self.player1)
            self.currentAttacker = 1
        end
        
        round = round + 1
    end
    
    -- 计算战斗结果
    local result = self:calculateResult(board1, board2)
    self:logEvent("战斗结束: " .. result.message)
    
    return result
end

-- 解析一次攻击
function Combat:resolveAttack(attackerBoard, defenderBoard, attackerPlayer, defenderPlayer)
    if #attackerBoard == 0 or #defenderBoard == 0 then return end
    
    -- 选择攻击者（最左边的随从）
    local attackerIndex = 1
    local attacker = attackerBoard[attackerIndex]
    
    -- 选择防御者
    local defenderIndex = self:selectDefender(defenderBoard, attacker)
    local defender = defenderBoard[defenderIndex]
    
    self:logEvent(attacker.name .. " 攻击 " .. defender.name)
    
    -- 触发攻击前效果
    self:triggerBeforeAttack(attackerBoard, attackerIndex, defenderBoard, defenderIndex, attackerPlayer, defenderPlayer)
    
    -- 计算伤害
    local attackerDamage = attacker.attack
    local defenderDamage = defender.attack
    
    -- 应用伤害
    defender.health = defender.health - attackerDamage
    attacker.health = attacker.health - defenderDamage
    
    self:logEvent(attacker.name .. " 造成 " .. attackerDamage .. " 点伤害")
    self:logEvent(defender.name .. " 造成 " .. defenderDamage .. " 点伤害")
    
    -- 检查死亡
    local deaths = {}
    if defender.health <= 0 then
        table.insert(deaths, {board = defenderBoard, index = defenderIndex, minion = defender, isDefender = true})
        self:logEvent(defender.name .. " 死亡")
    end
    if attacker.health <= 0 then
        table.insert(deaths, {board = attackerBoard, index = attackerIndex, minion = attacker, isDefender = false})
        self:logEvent(attacker.name .. " 死亡")
    end
    
    -- 处理死亡（从后往前移除避免索引问题）
    table.sort(deaths, function(a, b) return a.index > b.index end)
    for _, death in ipairs(deaths) do
        self:triggerDeath(death.board, death.index, death.minion, death.isDefender, 
                         death.isDefender and defenderPlayer or attackerPlayer)
        table.remove(death.board, death.index)
    end
    
    -- 触发攻击后效果
    self:triggerAfterAttack(attackerBoard, defenderBoard, attackerPlayer, defenderPlayer)
end

-- 选择防御者
function Combat:selectDefender(defenderBoard, attacker)
    -- 优先选择嘲讽随从
    local tauntMinions = {}
    for i, minion in ipairs(defenderBoard) do
        if minion.hasTaunt then
            table.insert(tauntMinions, i)
        end
    end
    
    if #tauntMinions > 0 then
        return tauntMinions[math.random(1, #tauntMinions)]
    end
    
    -- 没有嘲讽则随机选择
    return math.random(1, #defenderBoard)
end

-- 触发战斗开始效果
function Combat:triggerCombatStart(board, player)
    for i, minion in ipairs(board) do
        minion:onCombatStart(board, i, player)
    end
end

-- 触发攻击前效果
function Combat:triggerBeforeAttack(attackerBoard, attackerIndex, defenderBoard, defenderIndex, attackerPlayer, defenderPlayer)
    local attacker = attackerBoard[attackerIndex]
    local defender = defenderBoard[defenderIndex]
    
    attacker:onAttack(attackerBoard, attackerIndex, defenderBoard, defenderIndex, attackerPlayer)
    defender:onAttacked(defenderBoard, defenderIndex, attackerBoard, attackerIndex, defenderPlayer)
end

-- 触发死亡效果
function Combat:triggerDeath(board, index, minion, isDefender, player)
    minion:onDeath(board, index, player)
    
    -- 触发其他随从的亡语相关效果
    for i, otherMinion in ipairs(board) do
        otherMinion:onOtherDeath(board, i, minion, isDefender, player)
    end
end

-- 触发攻击后效果
function Combat:triggerAfterAttack(attackerBoard, defenderBoard, attackerPlayer, defenderPlayer)
    -- 可以在这里处理攻击后的全局效果
end

-- 计算战斗结果
function Combat:calculateResult(board1, board2)
    local remaining1 = #board1
    local remaining2 = #board2
    
    if remaining1 > 0 and remaining2 == 0 then
        return {winner = 1, damage = self:calculateDamage(board1), message = self.player1.name .. "获胜"}
    elseif remaining2 > 0 and remaining1 == 0 then
        return {winner = 2, damage = self:calculateDamage(board2), message = self.player2.name .. "获胜"}
    else
        -- 平局
        return {winner = 0, damage = 0, message = "平局"}
    end
end

-- 计算造成的伤害
function Combat:calculateDamage(board)
    local damage = 0
    for _, minion in ipairs(board) do
        damage = damage + minion.tier
    end
    return math.max(1, damage)
end

-- 记录战斗事件
function Combat:logEvent(message)
    table.insert(self.log, message)
end

-- 复制棋盘
function Combat:copyBoard(board)
    local newBoard = {}
    for _, minion in ipairs(board) do
        table.insert(newBoard, {
            id = minion.id,
            name = minion.name,
            tier = minion.tier,
            attack = minion.attack,
            health = minion.health,
            kingdom = minion.kingdom,
            skills = minion.skills,
            cost = minion.cost,
            isGolden = minion.isGolden,
            hasTaunt = minion.hasTaunt,
            onCombatStart = minion.onCombatStart,
            onAttack = minion.onAttack,
            onAttacked = minion.onAttacked,
            onDeath = minion.onDeath,
            onOtherDeath = minion.onOtherDeath
        })
    end
    return newBoard
end

return Combat